<template>
  <div class="home">
    <ul>
      <li v-for="item in messageList" :key="item.id">
        <p>{{ item.username }} {{ item.dateTime }}</p>
        <p>{{ item.message }}</p>
      </li>
    </ul>
    <input type="text" placeholder="请输入消息" v-model="message" @keyup.enter="sendMessage"/>
    <button type="button" @click="sendMessage">发送</button>
  </div>
</template>

<script>
const ws = new WebSocket('ws://localhost:8000')
export default {
  name: '',
  data() {
    return {
      message: '',
      username: '',
      messageList: []
    }
  },
  created() {
  },
  mounted() {
    this.username = localStorage.getItem('username')
    if (!this.username) {
      this.$router.push('/login')
      return
    }
    
    // 在这里绑定事件
    // 这两种写法都可以
    ws.addEventListener('open', this.handleOpen.bind(this), false)
    // ws.onopen = function () {
    //   console.log('连接成功')
    // }
    ws.addEventListener('close', this.handleClose.bind(this), false)
    ws.addEventListener('message', this.handleMessage.bind(this), false)
    ws.addEventListener('error', this.handleError.bind(this), false)
  },
  computed: {},
  methods: {
    sendMessage() {
      if (this.message === '') {
        return
      }
      // 发送消息到服务器
      ws.send(JSON.stringify({
        username: this.username,
        message: this.message,
        dateTime: new Date().toLocaleString(),
        id: Date.now()
      }))
      this.message = ''
    },
    handleOpen(e) {
      alert('连接成功')
      console.log('open', e);
    },
    handleClose(e) {
      console.log('close', e);
    },
    handleMessage(e) {
      console.log('message', e);
      this.messageList = [...this.messageList, JSON.parse(e.data)]
    },
    handleError(e) {
      alert('连接失败')
      console.log('error', e);
    }
    
  },
  
}
</script>

<style lang="scss" scoped>

</style>
